package cn.qingyun.gis.modules.express.util;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.CharPool;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.text.StrPool;
import cn.qingyun.gis.modules.express.util.constants.StrContext;

import java.util.List;
import java.util.TreeMap;
import java.util.stream.Collectors;

/**
 * @author WeiXiang
 * @Description ：URL解析方法
 */
public class URLUtil {

    /**
     * @param url 需要解析的url
     * @return TreeMap。
     */
    public static TreeMap<String, String> parsingURLToUri(String url) {
        String uri = CharSequenceUtil.subAfter(url, StrContext.QM, false);

        if (CharSequenceUtil.isNotBlank(uri)) {
            List<String> split = CharSequenceUtil.split(uri, CharPool.AMP);
            if (CollUtil.isNotEmpty(split)) {
                TreeMap<String, String> params = new TreeMap<>();
                for (String param : split) {
                    String key = CharSequenceUtil.subBefore(param, StrContext.EQ, false);
                    String value = CharSequenceUtil.subAfter(param, StrContext.EQ, false);
                    params.put(key, value);
                }
                if (CollUtil.isNotEmpty(params)) {
                    return params;
                }
            }
        }
        return new TreeMap<>();
    }


    /**
     * @param url 需要解析URL
     * @return 入参字段
     */
    public static String parsingURLToParam(String url) {

        //获取URI
        String uri = CharSequenceUtil.subAfter(url, StrContext.QM, false);

        if (CharSequenceUtil.isNotBlank(uri)) {
            List<String> split = CharSequenceUtil.split(uri, CharPool.AMP);
            if (CollUtil.isNotEmpty(split)) {
                List<String> collect = split.stream().map(item -> CharSequenceUtil.subBefore(item, StrContext.EQ, false)).collect(Collectors.toList());
                return String.join(StrPool.COMMA, collect);
            }
        }
        return null;
    }

}
